package com.zzty.springmybatis.common;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.zzty.springmybatis.entity.Clazz;
import com.zzty.springmybatis.entity.SelfExam;
import com.zzty.springmybatis.entity.SelfExamTransation;
import com.zzty.springmybatis.entity.TeamExam;
import com.zzty.springmybatis.entity.TeamExamTransation;
import com.zzty.springmybatis.service.ClazzService;
import com.zzty.springmybatis.service.SelfExamService;
import com.zzty.springmybatis.service.SelfExamTransationService;
import com.zzty.springmybatis.service.TeamExamService;
import com.zzty.springmybatis.service.TeamExamTransationService;

@Component
public class Quarzt {
	@Autowired
	SelfExamService selfExamService;
	@Autowired
	SelfExamTransationService selfExamTransationService;
	@Autowired
	TeamExamService teamExamService;
	@Autowired
	TeamExamTransationService teamExamTransationService;
	@Autowired
	ClazzService clazzService;

	@Scheduled(cron = "0 0 3 * * ?")
	public void excute() {
		List<Clazz> clazz = clazzService.getAllClazz();
		
		List<Integer> clazzid = new ArrayList<>();
		for(int i = 0 ; i<clazz.size();i++){
			clazzid.add(clazz.get(i).getId());
		}
		
		for(int i = 0 ; i<clazzid.size();i++){
			List<SelfExam> selfExam = selfExamService.searchSelfExamByWinnerIdAndClazzId(clazzid.get(i));
			for(int j = 0; j < selfExam.size(); j++){
				List<SelfExamTransation> selfExamTransation = selfExamTransationService.searchSETByExamId(selfExam.get(j).getId());
				for(int k = 0 ; k < selfExamTransation.size() ; k++){
					if("A".equals(selfExamTransation.get(k).getScore())){
						selfExamService.updateWinner(selfExamTransation.get(k).getExamId(), selfExamTransation.get(k).getUserId());						
					}
				}
			}
			List<TeamExam> teamExam = teamExamService.searchTeamExamByWinnerIdAndClazzId(clazzid.get(i));
			for(int j = 0; j < teamExam.size(); j++){
				List<TeamExamTransation> teamExamTransation = teamExamTransationService.searchInfoByExamId(teamExam.get(j).getId());
				for(int k = 0 ; k < teamExamTransation.size() ; k++){
					if("A".equals(teamExamTransation.get(k).getScore())){
						String[] id =  teamExamTransation.get(k).getUserIds().split("\\|");
						Integer winnerId1 = Integer.valueOf(id[0]);
						Integer winnerId2 = null;
						if (id.length != 1) {
							winnerId2 = Integer.valueOf(id[1]);
						}
						teamExamService.updateWinners(teamExamTransation.get(k).getExamId(), winnerId1, winnerId2);
					}
				}
			}
		}
	}
}
